package com.food.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.food.dao.service.CollectService;
import com.food.model.Collect;
import com.food.model.Member;

/**
 * Servlet implementation class CollectServlet
 */
@WebServlet("/recipe/CollectServlet")
public class CollectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
		int rid = Integer.parseInt(request.getParameter("rid"));
		HttpSession session = request.getSession();

		Member member = (Member)session.getAttribute("user");
		
		Collect collect = new Collect();
		collect.setRid(rid);
		collect.setMbid(member.getMbid());

		CollectService service = new CollectService();
		
		List<Collect> list = service.findCollectByMb(collect);
		for(Collect cl:list){
			if(cl.getRid()==rid){
				request.setAttribute("fail", "fail");
				RequestDispatcher rd = request
						.getRequestDispatcher("/recipe/ShowRecipe?rid="+rid);
				rd.forward(request, response);
				return;
			}
			
		}
		
		service.insertCollect(collect);
		request.setAttribute("success", "success");
		RequestDispatcher rd = request
				.getRequestDispatcher("/recipe/ShowRecipe?rid="+rid);
		rd.forward(request, response);
		return;
		
		
		}
		catch(Exception e){
			

			RequestDispatcher rd = request
					.getRequestDispatcher("../index.jsp");
			rd.forward(request, response);
			return;
		}
		
		
		
		
	}
	

}
